package com.tuanzi.loan.web.bean.businesssystem;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.businesssystem.BusinessIncome;
import com.tuanzi.loan.business.entity.businesssystem.BusinessMain;
import com.tuanzi.loan.business.entity.businesssystem.BusinessProduct;
import com.tuanzi.loan.business.service.businesssystem.BusinessIncomeService;
import com.tuanzi.loan.business.service.businesssystem.BusinessMainService;
import com.tuanzi.loan.business.service.businesssystem.BusinessProductService;
import com.tuanzi.loan.business.service.settlementsystem.SettlementIncomeActivityService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.businesssystem.BusinessIncomeRequest;
import com.tuanzi.loan.vo.response.businesssystem.BusinessIncomeResponse;
import com.tuanzi.loan.web.configuration.JSFListingBean;
import com.tuanzi.loan.web.lazy.businesssystem.BusinessIncomeLazyDataModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.tuanzi.loan.business.constants.DictionaryCode.*;

/**
 * @author caiwanlin
 * @create 2018-08-16 20:30
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class BusinessIncomeListBean extends JSFListingBean<BusinessIncomeRequest, BusinessIncomeResponse> {

    @Autowired
    private BusinessMainService settlementCompanyService;

    @Autowired
    private BusinessProductService settlementProductService;

    @Autowired
    private BusinessIncomeService settlementIncomeService;

    @Autowired
    private SettlementIncomeActivityService settlementIncomeActivityService;

    private List<BusinessProduct> productList;

    private List<BusinessMain> companyList;

    private BusinessIncome settlementIncome;//新增消耗记录

    private BusinessProduct businessProduct;//回显信息

    private Date endTime;

    private String header = "新增";

    private Long id;

    private Boolean enableMoreSave;

    private List<BusinessIncome> businessIncomes;

    private Double allIncome=0d;


    @PostConstruct
    public void init() throws Exception {
        companyList = settlementCompanyService.getCompanyList();
        productList = settlementProductService.getProductList();
        settlementIncome = new BusinessIncome();
        businessProduct = new BusinessProduct();
        enableMoreSave = false;
        businessIncomes = new ArrayList<BusinessIncome>(6);
        businessIncomes.add(new BusinessIncome());
        businessIncomes.add(new BusinessIncome());
        businessIncomes.add(new BusinessIncome());
        businessIncomes.add(new BusinessIncome());
        businessIncomes.add(new BusinessIncome());
        businessIncomes.add(new BusinessIncome());
        initLazyDataModel();
    }
    public void count(){
        allIncome = settlementIncomeService.getAllIncome($);
    }
    private void initLazyDataModel() throws Exception {
        $ = new BusinessIncomeRequest();
        lazyDataModel = new BusinessIncomeLazyDataModel($);
    }

    public void onReset() throws Exception {
        initLazyDataModel();
    }


    /**
     * 选择产品回显数据
     */
    public void onSelectProduct() {
        Long productId = id;
        if (productId == null) {
            settlementIncome = new BusinessIncome();
            return;
        }
        businessProduct = settlementProductService.findOne(productId);
        convertIncome(businessProduct);
    }
    
    public void onSelectDate() {
        if (enableMoreSave==true){
            Date beginDate = settlementIncome.getSettlementTime();
            for (int i=0;i<6;i++){
                businessIncomes.get(i).setSettlementTime(DateUtils.addDays(beginDate, i+1));
            }
        }
    }

    private void convertIncome(BusinessProduct settlementProduct) {
        settlementIncome = new BusinessIncome();
        settlementIncome.setChannelId(Long.valueOf(settlementProduct.getChannelId()));
        settlementIncome.setPayMode(settlementProduct.getPayMode());
        settlementIncome.setPricePay(settlementProduct.getPricePay());
        settlementIncome.setBelongAppId(settlementProduct.getBelongAppId());
        settlementIncome.setChannelType(settlementProduct.getChannelType());
        settlementIncome.setPayType(settlementProduct.getPayType());
        settlementIncome.setChannelMain(settlementProduct.getCompanyId());
    }
    public void onDelete(Long id) {
        BusinessIncome one = settlementIncomeService.findOne(id);
        try {
            settlementIncomeService.delete(one);
            settlementCompanyService.incomeDelete(one);
        }catch(Exception e) {
            e.printStackTrace();
        }
        addSuccessfullyMessage();
    }


    /**
     * 保存记录
     */
    public void onSave() {
        boolean validate = validate();
        if (validate == false) return;
        if (enableMoreSave==true){
            moreSave();
        }
        settlementIncomeService.onSave(settlementIncome);
        addSuccessfullyMessage();
        execute("PF('adding').hide();");
        update("incomeForm");
    }

    public void moreSave() {
        businessIncomes.forEach(x->{
            if (x.getSettlementTime()==null||x.getIncomeAmount()==null)
                return;
                BusinessIncome income = new BusinessIncome();
                BeanUtils.copyProperties(settlementIncome, income);
                income.setSettlementTime(x.getSettlementTime());
                income.setIncomeAmount(x.getIncomeAmount());
                settlementIncomeService.onSave(income);

        });
    }

    public void autoCount() {
        boolean validate = validate();
        if (validate == false) return;
        try {
            settlementIncomeService.autoCount(settlementIncome.getSettlementTime(), endTime);
        } catch (Exception e){
            e.printStackTrace();
            addFiledMessage("数据错误");
            return;
        }
        endTime=null;
        addSuccessfullyMessage();
        execute("PF('adding').hide();");
        update("incomeForm");
    }

    public boolean validate() {
        if (settlementIncome.getChannelId() == null) {
            addErrorMessage("没有选择渠道");
            return false;
        }
        if (settlementIncome.getSettlementTime() == null) {
            addErrorMessage("没有选择结算日期");
            return false;
        }
        if (settlementIncome.getIncomeAmount() == null && settlementIncome.getPayMode()!=1 && settlementIncome.getPayMode()!=2 && settlementIncome.getPayMode()!=7) {
            addErrorMessage("结算金额为空");
            return false;
        }
        if (endTime!=null&&settlementIncome.getSettlementTime().after(endTime)) {
            addErrorMessage("日期间隔错误");
            return false;
        }
        return true;
    }


    public void onAdd(String id) {
        header = "新增";
        settlementIncome = new BusinessIncome();
        if (StringUtils.isNotBlank(id)) {
            this.id=Long.valueOf(id);
            settlementIncome.setChannelId(Long.valueOf(id));
            onSelectProduct();
        }
    }

    public String onReturn(String url){
        return redirect(url,getParam());
    }

    public void onSee(Long id) {
        header = "编辑";
        settlementIncome = settlementIncomeService.findOne(id);
    }


    /**
     * 监听结算金额
     */
    public void onChangeIncomeAmount() {
        Integer copMode = settlementIncome.getPayMode();
        if (copMode == null) {
            return;
        }
        Double priceCpa = settlementIncome.getPricePay();
        Integer count = settlementIncome.getCount();
        settlementIncome.setIncomeAmount(priceCpa * count);

    }


    @Override
    protected List<String> getDictionaryCodes() {
        return Lists.newArrayList(SETTLEMENT_SPREAD_CHANNEL, SETTLEMENT_INCOME_TYPE,
                SETTLEMENT_SPREAD_MODE, COOPERATION_MODE, SETTLEMENT_CYCLE, SETTLEMENT_CATEGORY,
                SETTLEMENT_BILLING_CONTENT, SETTLEMENT_BILL_TYPE,CHANNEL_TYPE);
    }
}
